import React from 'react'
import { Link, withRouter } from 'react-router-dom';

class NavLink extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isActive: false,
        }
    }
    componentDidMount() {
        const { pathname } = this.props.location;
        this.setActive(pathname);
    }
    componentDidUpdate() {
        const { pathname } = this.props.location;
        this.setActive(pathname);
    }
    setActive(pathname) {
        const { exact = false } = this.props;
        let isActive = this.state.isActive;
        if (exact) {
            isActive = pathname === this.props.to;
        }
        else {
            const res = new RegExp('^' + this.props.to, 'g');
            isActive = res.test(pathname);
        }
        if (this.state.isActive != isActive) {
            this.setState({
                isActive: isActive
            })
        }
    }
    render() {
        const {
            activeClass,
            exact,
            className = '',
            staticContext,
            location,
            match,
            history,
            ...passThroughProps } = this.props;
        const classNames = this.state.isActive ? activeClass + ' ' + className : className;
        return (
            <Link {...passThroughProps} className={classNames}></Link   >
        )
    }
}
export default withRouter(NavLink)